const jsdom = require('sdenv-jsdom');
const logger = require("../../utils/logger");
const fs = require("fs");
const {JSDOM, CookieJar} = jsdom;

function getFile(filepath) {
    if (!filepath) throw new Error(`getFile: ${name}错误`);
    if (!fs.existsSync(filepath)) throw new Error(`文件${filepath}不存在`);
    return fs.readFileSync(filepath);
}

jsdomFromTextWithCookie = (config, cookieJar) => {
    const virtualConsole = new jsdom.VirtualConsole();
    virtualConsole.sendTo({
        log: logger.log.bind(logger),
        warn: logger.warn.bind(logger),
        error: logger.error.bind(logger),
    });
    if (!cookieJar) cookieJar = new CookieJar();
    const options = {
        pretendToBeVisual: true,
        cookieJar,
        virtualConsole,
        ...config,
    }
    return [(text) => {
        return new JSDOM(text, options);
    }, cookieJar];
}

module.exports = {
    jsdomFromTextWithCookie,
    getFile
}